package org.example.bookingsystem.Listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.example.bookingsystem.common.Constants;
import org.example.bookingsystem.mapper.BankMapper;
import org.example.bookingsystem.service.BankService;
import org.example.bookingsystem.service.SystemService;
import org.example.bookingsystem.utils.DateUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Component
public class Listener2 {
    @Autowired
    private BankService bankService;
    @Autowired
    private SystemService systemService;
    @RabbitListener(queues = Constants.REQUEST_QUEUE2)
    @SendTo(Constants.RESPONSE_QUEUE2) // 自动将响应发送到响应队列
    public String queryResponse(String message) throws JsonProcessingException {
        if ("true".equalsIgnoreCase(message)) {
            return "请选择支付方式";
        }else if (message.contains(",")){
            String[] array = message.split(",");
            int uid = Integer.parseInt(array[0]);
            int tid = Integer.parseInt(array[1]);
            int type = Integer.parseInt(array[2]);
            if(bankService.getBalance(uid)-systemService.selectTicketCost(tid)<0){
                return "余额不足支付失败";
            }else {
                int cost = systemService.selectTicketCost(tid);
                int oldbalance = bankService.getBalance(uid);
                bankService.updateBalance(uid,tid);
                int newbalance = bankService.getBalance(uid);
                // 获取当前时间
                LocalDateTime currentDateTime = LocalDateTime.now();

                // 将 LocalDateTime 转换为 Timestamp
                Timestamp timestamp = Timestamp.valueOf(currentDateTime);
                systemService.addOrder(uid,tid,cost,timestamp,type);
                systemService.updatepoll(tid);
                return "支付前余额："+oldbalance+","+"支付后余额"+newbalance+","+"祝您旅途愉快";
            }
        }
        return null;
    }
}
